<template>
  <div class="payment-container">
    <!-- 头部区域 -->
    <el-card class="header-card" shadow="hover">
      <div class="header-content">
        <div class="order-info">
          <h1 class="order-id">订单号: {{ order.orderId }}</h1>
          <div class="meta-info">
            <el-tag type="info" effect="dark" size="small">
              <i class="el-icon-user"></i>
              {{ order.userId }}
            </el-tag>
            <el-tag type="info" effect="dark" size="small">
              <i class="el-icon-date"></i>
              {{ formatTime(order.paymentTime) }}
            </el-tag>
          </div>
        </div>
        <el-divider direction="vertical" class="divider" />
        <div class="amount-wrapper">
          <div class="amount-label">应付金额</div>
          <div class="amount">￥{{ order.totalAmount }}</div>
        </div>
      </div>
    </el-card>

    <!-- 主体区域 -->
    <el-card class="main-card" shadow="never">
      <el-steps :active="activeStep" finish-status="success" simple>
        <el-step title="待支付" icon="el-icon-coin" />
        <el-step title="待发货" icon="el-icon-box" />
        <el-step title="已完成" icon="el-icon-circle-check" />
      </el-steps>

      <el-divider content-position="left">
        <i class="el-icon-location"></i> 收货信息
      </el-divider>

      <el-descriptions :column="1" border class="address-card">
        <el-descriptions-item label="收件人" label-class-name="desc-label">
          <el-tag size="small">{{ deliveryAddress.receiverName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话" label-class-name="desc-label">
          <el-link type="primary" :underline="false">
            {{ deliveryAddress.mobile }}
          </el-link>
        </el-descriptions-item>
        <el-descriptions-item label="详细地址" label-class-name="desc-label">
          {{ fullAddress }}
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">
        <i class="el-icon-warning"></i> 订单状态
      </el-divider>
      <div class="payment-tips">
        <el-alert
          :title="orderStatusText"
          :type="orderStatusType"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <!-- 底部操作 -->
    <div class="action-footer">
      <el-button
        type="success"
        size="large"
        :icon="order.paymentStatus === 1 ? 'el-icon-success' : 'el-icon-wallet'"
        @click="handlePay"
        :disabled="order.paymentStatus === 1"
        class="pay-button"
      >
        {{ order.paymentStatus === 1 ? "已支付" : "立即支付" }}
      </el-button>
      <div class="secondary-actions">
        <el-link type="info" :underline="false" @click="handleViewOrder">
          <i class="el-icon-document"></i> 查看订单详情
        </el-link>
        <el-link type="danger" :underline="false" @click="handleCancel">
          <i class="el-icon-close"></i> 取消订单
        </el-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";
import { OrderControllerService } from "@/generated";

const route = useRoute();
const router = useRouter();

interface Order {
  orderId: string;
  userId: string;
  totalAmount: number;
  paymentStatus: number;
  paymentTime: string;
  deliveryAddress: string;
  orderStatus: number;
}

interface Address {
  receiverName: string;
  mobile: string;
  province: string;
  city: string;
  district: string;
  detailAddress: string;
}

const order = ref<Order>({
  orderId: "",
  userId: "",
  totalAmount: 0,
  paymentStatus: 0,
  paymentTime: "",
  deliveryAddress: "",
  orderStatus: 0,
});

// 获取订单数据
const fetchOrderData = async () => {
  try {
    const orderId = route.params.orderId as string;
    const res = await OrderControllerService.getOrderById(orderId);
    if (res.code !== 0 || !res.data) {
      ElMessage.error("订单不存在");
      await router.push("/");
      return;
    }
    order.value = res.data;
  } catch (error) {
    console.error("获取订单数据失败:", error);
    ElMessage.error("获取订单信息失败");
    await router.push("/");
  }
};

// 计算完整地址
const fullAddress = computed(() => {
  const addr = deliveryAddress.value;
  return `${addr.province} ${addr.city} ${addr.district} ${addr.detailAddress}`;
});

// 订单状态显示
const orderStatusText = computed(() => {
  switch (order.value.orderStatus) {
    case 0:
      return "订单已创建，等待发货";
    case 1:
      return "商品已发货，运输途中";
    case 2:
      return "订单已完成";
    default:
      return "未知状态";
  }
});

const orderStatusType = computed(() => {
  switch (order.value.orderStatus) {
    case 0:
      return "info";
    case 1:
      return "warning";
    case 2:
      return "success";
    default:
      return "info";
  }
});

// 步骤激活状态
const activeStep = computed(() => {
  if (order.value.paymentStatus === 0) return 0;
  return order.value.orderStatus + 1;
});

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 收货地址解析
const deliveryAddress = computed<Address>(() => {
  try {
    return JSON.parse(order.value.deliveryAddress);
  } catch {
    return {
      receiverName: "",
      mobile: "",
      province: "",
      city: "",
      district: "",
      detailAddress: "",
    };
  }
});

// 支付处理
const handlePay = async () => {
  try {
    await ElMessageBox.confirm(
      `确认支付 ¥${order.value.totalAmount} 吗？`,
      "支付确认",
      {
        confirmButtonText: "确认支付",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const res = await OrderControllerService.payOrder(order.value.orderId);
    if (res.code === 0) {
      await fetchOrderData();
      // 提示用户，将在5秒后跳转到首页
      ElMessage.success(
        `支付成功，将在5秒后跳转到首页，您可以在个人中心查看订单详情。`
      );
      setTimeout(() => {
        router.push("/");
      }, 5000);
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    // 用户取消支付
    return;
  }
};

// 取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm("确定要取消订单吗？", "取消订单", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await OrderControllerService.deleteOrder(order.value.orderId);
    if (res.code === 0) {
      ElMessage.success("订单已取消");
      await router.push("/");
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    // 用户取消操作
  }
};

onMounted(() => {
  fetchOrderData();
});
</script>

<style scoped>
/* 保持原有样式不变 */
.payment-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.header-card {
  margin-bottom: 24px;
  border-radius: 12px;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
}

/* 其他样式保持不变... */
</style>
